import 'package:flutter/material.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:azlistview/azlistview.dart';
import 'package:xim/config/route_config.dart';
import 'package:xim/http/apis/user/user_api.dart';
import 'package:xim/http/apis/user/user_model.dart';
import 'package:xim/widget/common/state.dart';

/// 通讯录页面
class ChatBookScreen extends StatefulWidget {
  const ChatBookScreen({Key? key}) : super(key: key);

  @override
  State<ChatBookScreen> createState() => _ChatBookScreenState();
}

class _ChatBookScreenState extends AppBarState<ChatBookScreen> with BrightnessModeState<ChatBookScreen> {

  @override
  String get appBarTitle => "通讯录";

  /// 固定首部
  List<ContactModel> topList = [
    ContactModel('新的朋友', '#',
      bgColor: Colors.orange,
      iconData: Icons.person_add,
      onTab: Routers.toNewFriendsPage
    ),
    ContactModel('群聊', '#', bgColor: Colors.green, iconData: Icons.people),
    ContactModel('文件助手', '#', bgColor: Colors.blueAccent, iconData: Icons.file_copy_rounded),
  ];

  List<ContactModel> contactList = [];

  List<ContactModel> _handleList(List<ContactModel> list) {
    if (list.isEmpty) return topList;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }

    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(list);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(list);

    list.insertAll(0, topList);

    return list;
  }

  @override
  void initState() {
    super.initState();
    dataInit();
  }

  @override
  Widget build(BuildContext context) {
    initModelColor(context);
    return Scaffold(
        appBar: appBar,
        body: Container(
          // color: bgColor.color,
          constraints: const BoxConstraints(minHeight: double.infinity),
          child: AzListView(
              data: contactList,
              itemCount: contactList.length,
              itemBuilder: (BuildContext context, int index) {
                var model = contactList[index];
                return ListTile(
                  onTap: model.onTab,
                  leading: model.img != null
                      ? ClipRRect(
                          borderRadius: const BorderRadius.all(Radius.circular(8)),
                          child: Image.network(
                            model.img!,
                            width: 40,
                          ))
                      : Container(
                          width: 40,
                          height: 40,
                          decoration: BoxDecoration(
                              color: model.bgColor,
                              borderRadius: const BorderRadius.all(Radius.circular(8))),
                          child: Icon(
                            model.iconData!,
                            color: Colors.white,
                          ),
                        ),
                  title: Text(model.name, ),
                );
              },
              physics: const BouncingScrollPhysics(),
              susItemBuilder: (context, index) {
                var model = contactList[index];
                if ('#' == model.getSuspensionTag()) {
                  return const SizedBox();
                }
                return Container(
                  // color: bgColor.color,
                  height: 36,
                  width: MediaQuery.of(context).size.width,
                  padding: const EdgeInsets.only(left: 16.0),
                  alignment: Alignment.centerLeft,
                  child: Text(
                      style: const TextStyle(fontSize: 14, color: Color(0xFF666666)),
                      softWrap: false,
                      model.getSuspensionTag()
                  ),
                );
              },
              indexBarData: const ['↑', '☆', ...kIndexBarData],
              indexBarOptions: const IndexBarOptions(
                  needRebuild: true,
                  ignoreDragCancel: true,
                  downTextStyle: TextStyle(fontSize: 12, color: Colors.white),
                  downItemDecoration:
                      BoxDecoration(shape: BoxShape.circle, color: Colors.green),
                  indexHintWidth: 120 / 2,
                  indexHintHeight: 100 / 2,
                  indexHintAlignment: Alignment.centerRight,
                  indexHintChildAlignment: Alignment(-0.25, 0.0),
                  indexHintOffset: Offset(-20, 0),
                  indexHintTextStyle: TextStyle(  fontSize: 18))
          ),
        ));
  }

  dataInit() async {
    var friends = (await UserApi.queryFriends())
        .map((e) => ContactModel.fromUserFriendModel(e,
            onTab: ()=>Routers.toProfilePublicPage(e.friendUserInfo.account)))
        .toList();
    setState(() {
      contactList = _handleList(friends);
    });
  }

}

class ContactModel extends ISuspensionBean {
  final String name;
  String tagIndex;
  String? namePinyin;
  Color? bgColor;
  IconData? iconData;
  String? img;
  void Function()? onTab;

  ContactModel.fromUserFriendModel(UserFriendModel model, {this.onTab})
      : name = model.friendUserInfo.name,
        tagIndex = PinyinHelper.getFirstWordPinyin(model.friendUserInfo.name)[0].toUpperCase(),
        img = model.friendUserInfo.avatar;

  ContactModel(this.name, this.tagIndex, {this.bgColor, this.iconData, this.img, this.onTab});

  @override
  String getSuspensionTag() {
    return tagIndex ?? '';
  }
}
